<script setup lang="ts">
import type { FileType } from 'ant-design-vue/es/upload/interface';

import { Button, Upload, message } from 'ant-design-vue';
import { ref } from 'vue';

import { useVbenModal } from '@vben/common-ui';
import { downloadFileFromBlobPart } from '@vben/utils';

import {
  downloadHandCardAssetImportTemplate,
  importHandCardAsset,
} from '#/api/spa/handcard/asset';

defineOptions({
  name: 'HandCardImportModal',
});

interface Emits {
  (e: 'success'): void;
}

const emit = defineEmits<Emits>();

const uploadFile = ref<File | null>(null);

const [Modal, modalApi] = useVbenModal({
  confirmButtonText: '导入',
  async onConfirm() {
    if (!uploadFile.value) {
      message.warning('请先选择 Excel 文件');
      return;
    }

    modalApi.lock();
    try {
      await importHandCardAsset(uploadFile.value);
      message.success('手牌导入成功');
      emit('success');
      await modalApi.close();
    } finally {
      modalApi.unlock();
    }
  },
  async onOpenChange(isOpen) {
    if (!isOpen) {
      uploadFile.value = null;
    }
  },
});

const beforeUpload = (file: FileType) => {
  uploadFile.value = file as File;
  return false;
};

const handleDownloadTemplate = async () => {
  const data = await downloadHandCardAssetImportTemplate();
  downloadFileFromBlobPart({ fileName: '手牌导入模板.xls', source: data });
};
</script>

<template>
  <Modal title="批量导入手牌" class="w-1/3">
    <div class="space-y-4 px-1 py-2">
      <div>
        <div class="mb-2 text-sm text-gray-600">选择需要导入的 Excel 文件</div>
        <Upload
          :max-count="1"
          accept=".xls,.xlsx"
          :before-upload="beforeUpload"
        >
          <Button type="primary">选择文件</Button>
        </Upload>
        <div v-if="uploadFile" class="mt-2 text-xs text-gray-500">
          已选择：{{ uploadFile.name }}
        </div>
      </div>

      <div class="flex items-center gap-2 text-sm">
        <span>还没有模板？</span>
        <Button type="link" @click="handleDownloadTemplate">
          下载导入模板
        </Button>
      </div>

      <ul class="list-disc space-y-1 pl-5 text-xs text-gray-500">
        <li>仅支持 .xls / .xlsx 文件格式</li>
        <li>请先下载模板，按照示例填充手牌数据后再上传</li>
        <li>同一个文件不要重复导入，避免生成重复数据</li>
      </ul>
    </div>
  </Modal>
</template>

